﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TaoNiuOA.Models;
using System.Transactions;

namespace TaoNiuOA.Web.Controllers
{
    public class UserController : Controller
    {
        private DbEntity db = new DbEntity();

        [IsAdmin]
        public ViewResult Index()
        {

            return View(db.Users.ToList());
        }

        [IsAdmin]
        public ViewResult Details(int id)
        {
            User user = db.Users.Find(id);
            return View(user);
        }

        //get,登录
        public ViewResult Logon()
        {
            return View();
        }

        //post,登录
        [HttpPost]
        public ActionResult Logon(LogOnModel log)
        {
            var username = log.UserName;
            var pass = ShenLan.Common.Encrypt.EnctyptPassword(log.Password);
            var user = db.Users.SingleOrDefault(n => n.UserName == username && n.Password == pass);
            if (user == null)
            {
                ViewData["error"] = "用户名或密码错误,请重新输入.";
                return View(log);
            }
            else
            {
                //判断是否已经禁用账号
                if (user.Status == 0)
                {
                    ViewData["error"] = "您的账号已经禁用,如有问题请联系管理员.";
                    return View(log);
                }

                Session["users"] = user;
                //更新上次登录时间
                db.Entry(user).State = EntityState.Modified;
                user.LastActivityTime = DateTime.Now;
                db.SaveChanges();

                //更新任务的持续天数,
                //状态为2的,即为执行中的任务
                var executingList = db.Tasks.Where(n => n.Status == 2);
                foreach (var task in executingList)
                {
                    task.LastDays = Convert.ToDouble((DateTime.Now - Convert.ToDateTime(task.StartTime)).TotalDays.ToString("f2"));//ToString("0.00"));
                    var sql = string.Format("update [tasks] set [lastDays]='{0}' where [taskid]='{1}'", task.LastDays, task.TaskID);
                    db.Database.ExecuteSqlCommand(sql);
                }

                var today = DateTime.Now.ToString("yyyy-MM-dd");
                var check = db.Checkings.SingleOrDefault(n => n.UserID == user.UserID && n.Date == today);
                if (check == null)
                {
                    check = new Checking();
                    check.UserID = user.UserID;
                    check.Date = today;
                    db.Checkings.Add(check);
                    db.SaveChanges();
                }

                //跳回登录前页面
                var returnUrl = Request.QueryString["returnUrl"];
                if (!string.IsNullOrEmpty(returnUrl))
                    return Redirect(returnUrl);
                else
                    return RedirectToAction("Index", "Home");
                return View();
            }
        }

        //
        // GET: 注册用户

        public ActionResult Reg()
        {
            return View();
        }

        //注册
        [HttpPost]
        public ActionResult Reg(RegisterModel regModel)
        {
            if (ModelState.IsValid)
            {
                var dbUsers = db.Users.ToList();

                //判断用户是否已经存在
                foreach (var u in dbUsers)
                {
                    if (u.UserName == regModel.UserName)
                    {
                        ModelState.AddModelError("UserName", "该用户名已经存在");
                        return View(regModel);
                    }
                }

                //事务,保持数据一致
                using (TransactionScope ts = new TransactionScope())
                {
                    //初始化用户信息
                    var userinfo = new UserInfo();
                    db.UserInfoes.Add(userinfo);
                    db.SaveChanges();

                    //用户权限
                    var userRole = new UserRole();
                    userRole.Apply = false;
                    userRole.Department = false;
                    userRole.TaskAdd = false;
                    userRole.TaskApprove = false;
                    userRole.User = false;
                    userRole.UserGroup = false;
                    db.UserRoles.Add(userRole);
                    db.SaveChanges();

                    //执行注册
                    var user = new TaoNiuOA.Models.User();
                    user.Email = regModel.Email;
                    user.LastActivityTime = DateTime.Now;
                    user.Password = ShenLan.Common.Encrypt.EnctyptPassword(regModel.Password);
                    user.PasswordQuestion = regModel.PasswordQuestion;
                    user.PasswordAnswer = regModel.PasswordAnswer;
                    user.RegTime = DateTime.Now;
                    user.Status = 1;
                    user.UserGroupID = 0;
                    user.UserInfoID = userinfo.UserInfoID;
                    user.UserRoleID = userRole.UserRoleID;
                    user.UserName = regModel.UserName;
                    db.Users.Add(user);
                    db.SaveChanges();

                    ts.Complete();
                }
                return RedirectToAction("Index");
            }

            return View(regModel);
        }


        // GET: 管理员添加用户
        [IsAdmin]
        public ActionResult AddUser()
        {
            return View();
        }

        //管理员添加用户
        [IsAdmin]
        [HttpPost]
        public ActionResult AddUser(AddUserModel add)
        {
            if (ModelState.IsValid)
            {
                var dbUsers = db.Users.ToList();

                //判断用户是否已经存在
                foreach (var u in dbUsers)
                {
                    if (u.UserName == add.UserName)
                    {
                        ModelState.AddModelError("UserName", "该用户名已经存在");
                        return View(add);
                    }
                }

                //事务,保持数据一致
                using (TransactionScope ts = new TransactionScope())
                {
                    //初始化用户信息
                    var userinfo = new UserInfo();
                    db.UserInfoes.Add(userinfo);
                    db.SaveChanges();

                    //用户权限
                    var userRole = new UserRole();
                    userRole.Apply = false;
                    userRole.Department = false;
                    userRole.TaskAdd = false;
                    userRole.TaskApprove = false;
                    userRole.User = false;
                    userRole.UserGroup = false;
                    db.UserRoles.Add(userRole);
                    db.SaveChanges();

                    //执行注册
                    var user = new TaoNiuOA.Models.User();
                    user.Email = "";
                    user.LastActivityTime = DateTime.Now;
                    user.Password = ShenLan.Common.Encrypt.EnctyptPassword(add.Password);
                    user.PasswordQuestion ="";
                    user.PasswordAnswer = "";
                    user.RegTime = DateTime.Now;
                    user.Status = 1;
                    user.UserGroupID = 0;
                    user.UserInfoID = userinfo.UserInfoID;
                    user.UserRoleID = userRole.UserRoleID;
                    user.UserName = add.UserName;
                    db.Users.Add(user);
                    db.SaveChanges();

                    ts.Complete();
                }
                return RedirectToAction("Index");
            }

            return View(add);
        }

        // 注销登录
        public ActionResult Logoff()
        {
            Session["users"] = null;
            return RedirectToAction("Index", "Home");
        }

        //编辑用户信息
        [IsAdmin]
        public ActionResult Edit(int id)
        {
            User user = db.Users.Find(id);
            ViewBag.DepartmentID = new SelectList(db.Departments, "DepartmentID", "Name", user.DepartmentID);
            ViewBag.UserGroupID = new SelectList(db.UserGroups, "UserGroupID", "GroupName", user.UserGroupID);
            
            //状态
            var status = user.Status;
            var sli = new List<SelectListItem>();
            sli.Add(new SelectListItem { Value = "0", Text = "禁用" });
            sli.Add(new SelectListItem { Value = "1", Text = "正常" });
            ViewBag.Status = new SelectList(sli, "Value", "Text", status);

            return View(user);
        }

        //编辑用户信息
        [IsAdmin]
        [HttpPost]
        public ActionResult Edit(User user)
        {
            if (ModelState.IsValid)
            {
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(user);
        }

        public ActionResult Delete(int id)
        {
            User user = db.Users.Find(id);
            return View(user);
        }

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            User user = db.Users.Find(id);
            db.Users.Remove(user);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}